//import AudioSfxConfig from "../config/AudioSfxConfig";
import GameConfig from "../config/GameConfig";
import Utils from "../utils/Utils";

/**
 * 音效管理
 */
export default class AudioManager {

    private static _instance: AudioManager;

    /**音乐状态 */
    private _musicStatus: string = GameConfig.audioStatus.ON;
    /**音效状态 */
    private _effectStatus: string = GameConfig.audioStatus.ON;
    /**背景音乐id*/
    private _curMusicId: number = null;
    /**音效id */
    private _curEffectId: number = -1;

    /**背景音乐声音大小*/
    private _musicVolume: number = 1;
    /**音效声音大小 */
    private _effectVolume: number = 1;
    /**音量大小 */
    private _volume: number = 1;
    /**背景音乐资源 */
    private bgmUrl: string;

    private cacheEffect: Object = {};

    private cashAudioClip = {};

    private audioList: any = {};

    private playList = {};
    constructor() {
        let status = Utils.getItem(GameConfig.gameName + "sound");
        let audioVolume = Utils.getItem(GameConfig.gameName + "audioVolume");
        console.log("audioVolume",audioVolume)
        if (audioVolume) {
            audioVolume = JSON.parse(audioVolume)
            if (audioVolume["sound_vol"]) {
                GameConfig.audioVolume.sound_vol = parseFloat(audioVolume["sound_vol"])
            }
            if (audioVolume["music_vol"]) {
                GameConfig.audioVolume.music_vol = parseFloat(audioVolume["music_vol"])
            }
        }
        this.setVolume();
        if (status) {
            this._musicStatus = status;
            this._effectStatus = status;
            //this.setAudioStatus(status);
        } else {
            //this.setAudioStatus(GameConfig.audioStatus.ON);
        }
        
    }

    public static get Inst(): AudioManager {
        if (!this._instance) this._instance = new AudioManager();
        return this._instance;
    }
    /**获取状态 */
    public get status() {
        return this._musicStatus;
    }
    /**获取当前音乐名称 */
    public get bgmName() {
        return this.bgmUrl;
    }
    /**设置游戏音乐 */
    public setAudioStatus(status: string) {
        if (!status) return;
        if (status != GameConfig.audioStatus.ON && status != GameConfig.audioStatus.OFF) return cc.error("error status");
        this._volume = (status == GameConfig.audioStatus.ON ? 1 : 0);
        this._musicVolume = this._effectVolume = this._volume;
        cc.audioEngine.setEffectsVolume(this._volume * 0.6);
        cc.audioEngine.setMusicVolume(this._volume);
        Utils.setItem(GameConfig.gameName + "sound", status);
        this.setMusicStatus(status);
        // this.setEffectStatus(status);
    }
    /**设置音乐音量 */
    public setVolume() {
        cc.audioEngine.setEffectsVolume(this._volume * 0.75 * GameConfig.audioVolume.sound_vol);
        cc.audioEngine.setMusicVolume(this._volume* GameConfig.audioVolume.music_vol);
        Utils.setItem(GameConfig.gameName + "audioVolume", GameConfig.audioVolume);
    }
    /**
     * 设置音乐状态
     * @param status 状态
     */
    public setMusicStatus(status: string) {
        if (status != GameConfig.audioStatus.ON && status != GameConfig.audioStatus.OFF) return cc.error("error type");
        this._musicStatus = status;
        if (status == GameConfig.audioStatus.ON) {
            this.playMusic(this.bgmUrl);
        } else {
            this.stopMusic();
        }
    }
    /**
    * 设置音效状态
    * @param status 状态
    */
    public setEffectStatus(status: string) {
        if (status != GameConfig.audioStatus.ON && status != GameConfig.audioStatus.OFF) return cc.error("error type");
        this._effectStatus = status;
        if (status == GameConfig.audioStatus.OFF) {
            this.stopAllEffects();
        }
    }
    /**
     * 播放背景音乐
     */
    public playMusic(file: string | cc.AudioClip, loop: boolean = true) {
        if (!file) return;
        if (typeof file == "string") {
            this.bgmUrl = file;
            cc.resources.load("sound/" + file, cc.AudioClip, null, (error, audioClip: cc.AudioClip) => {
                if (this.bgmUrl !== file) return;
                this.playMusic(audioClip, loop);
            });
        } else {
            this.stopMusic();
            this._curMusicId = cc.audioEngine.playMusic(file, loop);
        }
    }
    /**
     * 停止播放背景音效
     *  */
    public stopMusic() {
        cc.audioEngine.stopMusic();
    }
    /**
     * 播放音效
     */
    public playEffect(file: string | cc.AudioClip, callBack: Function = null, loop: boolean = false, cache: boolean = false) {
        if (typeof file == "string") {
            cc.resources.load("sound/" + file, cc.AudioClip, null, (error, audioClip: cc.AudioClip) => {
                if (error) {
                    if (callBack) callBack();
                    return;
                }
                this.playEffect(audioClip, callBack, loop, cache);
            });
        } else {
            let aId = cc.audioEngine.playEffect(file, loop);
            this.SetCallBack(aId, callBack);
            // console.log("play id:" + aId + ",key:" + file.name + ",pTime:" + new Date().getTime());
            if (loop || cache) {
                this.cacheEffect[file.name] = { lId: -1, aId: aId };
            }
        }
    }
    // private loopId = -1;
    // private loopConfig = {};

    /**显示缓存列表id */
    showIds() {
        let arr = []
        for (let key in cc.audioEngine["_id2audio"]) {
            arr.push(key)
        }
        console.log(arr.join(","))
    }
    /**设置回调 */
    SetCallBack(id: number, callBack: Function) {
        let callFunc = () => {
            if (callBack) callBack();
            this.clearCache(id);
        }
        cc.audioEngine.setFinishCallback(id, callFunc);
    }
    clearCache(id: number) {
        for (let key in this.cacheEffect) {
            if (this.cacheEffect.hasOwnProperty(key) && this.cacheEffect[key] == id) {
                delete this.cacheEffect[key];
                break;
            }
        }
    }
    /**
     * 停止音效
     * @param key
     */
    public stopEffect(key?: string) {
        if (!key) {
            this.stopAllEffects();
        } else {
            this.stopLoop(key);
        }
    }
    /**
     * 停止所有音效
     */
    public stopAllEffects() {
        cc.audioEngine.stopAllEffects();
        for (let key in this.cacheEffect) {
            this.stopLoop(key)
        }
        this.playList = {};
    }
    /**停止循环音效 */
    public stopLoop(key: string) {
        // cc.audioEngine.stopAllEffects();
        let cfg = this.cacheEffect[key];
        if (cfg) {
            let aId = cfg.aId;
            let result: any = cc.audioEngine.stopEffect(aId);
            this.stopListAid(aId, !result);
            clearTimeout(cfg.lId);
            this.cacheEffect[key].loop = false;
            // console.log("stop id:" + aId + ",success:" + result);
        }
    }
    stopListAid(aId: any, stop: boolean) {
        if (this.audioList[aId]) {
            if (stop) {
                // console.warn(this.audioList[aId])
                this.audioList[aId].pause();
                this.audioList[aId].currentTime = 0;
                // console.warn("stop list aid:" + aId);
            }
            // delete this.audioList[aId];
            // console.log(this.audioList[aId]);
        }
    }
}
